/**
 * 
 */
package wangjg.xuexiban.util;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.google.gson.reflect.TypeToken;

import wangjg.xuexiban.entity.Category;
import wangjg.xuexiban.entity.SimpleCard;
import wangjg.xuexiban.util.json.GsonUtil;
import wangjg.xuexiban.vo.JsonResponse;
import wangjg.xuexiban.vo.PageData;

/**
 * @author wangjg
 *
 */
public class JsonUtil {

	public static JsonResponse json2response(String responseJson) {
		JsonResponse response = null;
		try {
			JSONTokener tokener = new JSONTokener(responseJson);
			JSONObject jo = (JSONObject) tokener.nextValue();
			response = new JsonResponse();
			response.setStatus(jo.getString("code"));
			if(!jo.isNull("message")){
				response.setMessage(jo.getString("message"));
			}
			if(!jo.isNull("data")){
				response.setData(jo.getString("data"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	public static JsonResponse getCgListResp(String respJson){
		JsonResponse response = json2response(respJson);
		if(response.noError()){
			PageData<Category> pageData = JsonUtil.json2PageCgList((String)response.getData());
			response.setData(pageData);
		}
		return response;
	} 

	public static JsonResponse getCardListResp(String respJson){
		JsonResponse response = json2response(respJson);
		if(response.noError()){
			PageData<SimpleCard> pageData = JsonUtil.json2PageCdList((String)response.getData());
			response.setData(pageData);
		}
		return response;
	}
	
	private static PageData<SimpleCard> json2PageCdList(String objJson){
		if(objJson.startsWith("{")){
			TypeToken<PageData<SimpleCard>> tt = new TypeToken<PageData<SimpleCard>>(){};
			PageData<SimpleCard> pd = GsonUtil.json2bean(objJson, tt.getType());
			return pd;
		}else{
			PageData<SimpleCard> pd = new PageData<SimpleCard>();
			Type type = new TypeToken<List<SimpleCard>>(){}.getType();
			List<SimpleCard> list = GsonUtil.json2bean(objJson, type);
			pd.setList(list);
			return pd;
		}
	}
	
	private static PageData<Category> json2PageCgList(String objJson){
		if(objJson.startsWith("{")){
			TypeToken<PageData<Category>> tt = new TypeToken<PageData<Category>>(){};
			PageData<Category> pd = GsonUtil.json2bean(objJson, tt.getType());
			return pd;
		}else{
			PageData<Category> pd = new PageData<Category>();
			Type type = new TypeToken<List<Category>>(){}.getType();
			List<Category> list = GsonUtil.json2bean(objJson, type);
			pd.setList(list);
			return pd;
		}
	}
	
}
